import os
import re
import shutil
import time

import bs4
import facade
from bs4 import BeautifulSoup
from vip.id_encode import GetLngid
from xjlibrary.mdatetime.mtime import getTodayDate
from xjlibrary.our_file_dir import BaseDir

curPath = BaseDir.get_file_dir_absolute(__file__)
TopPath = BaseDir.get_upper_dir(curPath, -2)
sPath = BaseDir.get_new_path(TopPath, "download", "shusheng_imut", "download", "detail1")
cover_path = BaseDir.get_new_path(TopPath, "download", "shusheng_imut", "download", "cover")
db3dir = BaseDir.get_new_path(TopPath, "download", "shusheng_imut", "download", "db3")
BaseDir.create_dir(db3dir)
temp_Path = BaseDir.get_new_path(curPath, "template")

configfile = BaseDir.get_new_path(curPath, "db.ini")


class Paradetail(object):

    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.BASE_URL = 'http://202.207.22.16:9988'
        self.isbn_reg = re.compile(r'(\w+(-\w+){3,})')
        self.year_reg = re.compile(r">\d{4}-\d{2}-\d{2}")
        self.publisher_reg = re.compile(r'[\u4e00-\u9fa5]+出版社')
        self.results = []
        self.sql = "insert or ignore into modify_title_info_zt(lngid,rawid,title,creator,description,date,date_created,language,country,provider,provider_url,provider_id,type,cover,medium,batch,publisher,identifier_pisbn,title_series,folio_size)  VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?);"
        self.templatedb3 = BaseDir.get_new_path(temp_Path, "zt_template.db3")
        self.new_db3_path = self.copyTempDB3(self.templatedb3, db3dir)
        self.db3_zt = facade.Sqlite3Utiles(logger=self.logger).Sqlite3DBConnectFromFilePath(
            self.new_db3_path, encoding="utf-8")

    def copyTempDB3(self, temp_path, copy_out):
        """
        拷贝创建新的db3文件
        :param temp_path: 模板db3文件路径
        :param copy_out: 新的db3输出路径
        :return: 新db3路径
        """
        today_str = str(getTodayDate())
        if not os.path.isfile(temp_path) or not os.path.isdir(copy_out):
            raise FileNotFoundError
        new_db3_name = 'zt_mirrorimutshushengbook_' + today_str + '.db3'
        new_db3_path = os.path.join(copy_out, new_db3_name)
        shutil.copyfile(temp_path, new_db3_path)
        return new_db3_path

    def para(self):
        language = "ZH"
        type = "1"
        medium = "2"
        country = "CN"
        batch = time.strftime('%Y%m%d') + "00"

        sub_db_id = "00249"
        product = "SHUSHENGTS"
        sub_db = "IMUT"
        provider_zt = "mirrorimutshushengbook"
        provider = "SHUSHENG"

        for filepath in BaseDir.get_dir_all_files(sPath):
            html = BaseDir.single_read_file(filepath, encoding="GB18030")
            (title, description, date_created, publisher, isbn, title_series, creator,
             folio_size) = self._parse_detail_one(html)
            folio_size = folio_size.replace("开", "").strip()
            # rawid, _, _ = file.partition('.')
            rawid = BaseDir.get_filename_not_extsep(filepath)
            if date_created:
                date = date_created[:4]
            else:
                date = '1900'
            if not date_created:
                date_created = '19000000'
            provider_url = provider_zt + "@" + self.BASE_URL + "/book_detail.action?bookId=" + rawid
            provider_id = provider_zt + "@" + rawid
            cover_file = rawid[:2] + "/" + rawid + '.jpg'
            if os.path.exists(os.path.join(cover_path, cover_file)):
                cover = '/smartlib/' + provider_zt + '/' + cover_file
            else:
                cover = ''
            lngid = GetLngid(sub_db_id, rawid)
            self.results.append(
                (
                    lngid, rawid, title, creator, description, date, date_created, language, country, provider_zt,
                    provider_url, provider_id, type, cover, medium, batch, publisher, isbn, title_series, folio_size
                ))
            if len(self.results) > 1000:
                self.execsql()
        self.execsql()

    def execsql(self):
        self.db3_zt.ExeSqlliteMany(self.sql, self.results)
        self.results.clear()

    def _parse_detail_one(self, html):
        title = ""
        description = ""
        date_created = ""
        publisher = ""
        isbn = ""
        title_series = ""
        creator = ""
        folio_size = ""
        soup = BeautifulSoup(html, 'lxml')
        intro_tag = soup.select_one('table[height="130"] td[class="12Black"]')
        title_creator_tag = soup.select_one('tr[valign="MIDDLE"] > td[class="12Black"]')
        try:
            description = intro_tag.string.strip()
        except AttributeError as e:
            pass
        for xx in title_creator_tag.find_all("strong"):
            # print(title_creator_tag.find_all("strong"))
            if xx.string.strip().find("丛书") >= 0:
                title_series = xx.next_sibling.strip()
            elif xx.string.strip().find("书名") >= 0:
                title = xx.next_sibling.strip()
                title = title.replace("《", "").replace("》", "")
            elif xx.string.strip().find("作者") >= 0:
                creator = xx.next_sibling.strip()
            elif xx.string.strip().find("开本") >= 0:
                folio_size = xx.next_sibling.strip()
            elif xx.strip() == "" or xx.strip() == "全 文" or xx.strip() == "借阅":
                pass
            else:
                raise Exception("有其他数据没有解析,请加入：" + xx)

        for item in title_creator_tag.contents:
            if not isinstance(item, bs4.element.Comment):
                continue
            isbn_tmp = self.isbn_reg.findall(item.string)
            year_tmp = self.year_reg.findall(item.string)
            publisher_tmp = self.publisher_reg.findall(item.string)
            if isbn_tmp:
                isbn = isbn_tmp[0][0]
                if isbn == "":
                    isbn_reg = re.compile(r">ISBN号：</strong>(.*?)<br>")
                    isbn = isbn_reg.findall(item.string)
                    isbn = isbn[0].replace("\x1f", "")
            if year_tmp:
                date_created = year_tmp[0].replace("-", "").replace(">", "")
            if publisher_tmp:
                publisher = publisher_tmp[0]


        # 一小部分特殊情况才有
        try:
            for item in title_creator_tag.peterson.contents:
                if not isinstance(item, bs4.element.Comment):
                    continue
                isbn_tmp = self.isbn_reg.findall(item.string)
                year_tmp = self.year_reg.findall(item.string)
                publisher_tmp = self.publisher_reg.findall(item.string)
                if isbn_tmp:
                    isbn = isbn_tmp[0][0]
                    if isbn == "":
                        isbn_reg = re.compile(r">ISBN号：</strong>(.*?)<br>")
                        isbn = isbn_reg.findall(item.string)
                        isbn = isbn[0].replace("\x1f", "")
                if year_tmp:
                    date_created = year_tmp[0].replace("-", "").replace(">", "")
                if publisher_tmp:
                    publisher = publisher_tmp[0]
        except:
            pass

        if creator == "无":
            creator = ''

        return title, description, date_created, publisher, isbn.replace('-', ''), title_series, creator, folio_size


if __name__ == "__main__":
    para = Paradetail()
    para.para()
